/**
 * 页面结构验证器
 * 确保生成的HTML页面严格符合 generate-page.md 中的规范
 */

export interface PageValidationResult {
  isValid: boolean
  errors: PageValidationError[]
  warnings: PageValidationWarning[]
  suggestions: string[]
  score: number // 0-100 合规性评分
}

export interface PageValidationError {
  type: 'structure' | 'class' | 'element' | 'javascript' | 'path' | 'template'
  message: string
  location?: string
  suggestion?: string
}

export interface PageValidationWarning {
  type: 'style' | 'accessibility' | 'performance' | 'compatibility' | 'structure' | 'javascript'
  message: string
  suggestion?: string
}

export type PageType = 'list' | 'form' | 'detail'

interface PageValidationRules {
  requiredClasses: string[]
  requiredElements: string[]
  forbiddenElements?: string[]
  requiredAttributes?: { [element: string]: string[] }
  pathPattern: RegExp
  cssFiles: string[]
  jsPatterns?: RegExp[]
  forbiddenJsPatterns?: RegExp[]
}

export class PageValidator {
  
  private static readonly VALIDATION_RULES: Record<PageType, PageValidationRules> = {
    list: {
      requiredClasses: ['container', 'data-table', 'action-buttons', 'search-area', 'search-form', 'button', 'text'],
      requiredElements: ['table', 'thead', 'tbody', 'div#app'],
      cssFiles: ['funi-framework.css', 'funi-components.css', 'funi-themes.css', 'funi-list.css'],
      pathPattern: /pages\/[^\/]+\/list\.html$/,
      jsPatterns: [
        /function\s+viewDetail\s*\(/,
        /window\.top\.location\.hash/,
        /class="button text"/,
        /handleViewAction/,
        /handleEditAction/,
        /handleDeleteAction/
      ],
      forbiddenJsPatterns: [
        /class="funi-btn funi-btn-text"/,
        /class="btn"/,
        /window\.location\.href/
      ]
    },
    form: {
      requiredClasses: ['form-container', 'form-grid', 'form-item-row', 'form-item-label', 'form-item-value', 'form-section-title'],
      requiredElements: ['form', 'div.form-section-title', 'div#app', 'div.form-container'],
      cssFiles: ['funi-framework.css', 'funi-components.css', 'funi-themes.css', 'funi-form.css'],
      pathPattern: /pages\/[^\/]+\/add-edit\.html$/,
      jsPatterns: [
        /window\.pageState\s*=\s*window\.pageState\s*\|\|/,
        /function\s+resetPageState\s*\(/,
        /function\s+initPageData\s*\(/,
        /class="form-grid"/
      ],
      forbiddenJsPatterns: [
        /let\s+isInitialized/,
        /var\s+currentStep/,
        /window\.location\.href/,
        /class="button"/
      ]
    },
    detail: {
      requiredClasses: ['form-container', 'form-grid', 'form-item-row', 'form-item-label', 'form-item-value', 'detail-header', 'funi-tabs'],
      requiredElements: ['div.detail-header', 'div#app', 'div.form-container', 'div.funi-tabs'],
      cssFiles: ['funi-framework.css', 'funi-components.css', 'funi-themes.css', 'funi-form.css'],
      pathPattern: /pages\/[^\/]+\/detail-review\.html$/,
      jsPatterns: [
        /window\.pageState\s*=\s*window\.pageState\s*\|\|/,
        /function\s+resetPageState\s*\(/,
        /data-tab/,
        /tab-item/
      ],
      forbiddenJsPatterns: [
        /let\s+isInitialized/,
        /var\s+currentStep/,
        /window\.location\.href/,
        /class="button"/
      ]
    }
  }

  /**
   * 验证页面结构是否符合规范
   */
  static async validatePageStructure(html: string, pageType: PageType): Promise<PageValidationResult> {
    const result: PageValidationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      suggestions: [],
      score: 100
    }

    const rules = this.VALIDATION_RULES[pageType]

    // 检查基本结构
    this.checkBasicStructure(html, rules, result)

    // 检查CSS类名
    this.checkCSSClasses(html, rules, result)

    // 检查必需元素
    this.checkRequiredElements(html, rules, result)

    // 检查CSS文件引用
    this.checkCSSFiles(html, rules, result)

    // 检查JavaScript架构（如果有要求）
    if (rules.jsPatterns || rules.forbiddenJsPatterns) {
      this.checkJavaScriptArchitecture(html, rules, result)
    }

    // 特定页面类型的检查
    this.checkPageSpecificRules(html, pageType, result)

    // 🆕 CSS框架兼容性验证
    await this.validateCSSFrameworkCompatibility(html, pageType, result)

    // 计算最终分数
    result.score = this.calculateScore(result)
    result.isValid = result.errors.length === 0 && result.score >= 80

    return result
  }

  /**
   * 验证CSS框架兼容性
   */
  private static async validateCSSFrameworkCompatibility(html: string, pageType: PageType, result: PageValidationResult): Promise<void> {
    try {
      const { CSSFrameworkValidator } = await import('./css-framework-validator.js')
      const cssResult = await CSSFrameworkValidator.validateCSSCompatibility(html, pageType)

      // 合并CSS验证结果
      result.errors.push(...cssResult.errors.map(error => ({
        type: error.type as any,
        message: `[CSS框架] ${error.message}`,
        location: error.location,
        suggestion: error.suggestion
      })))

      result.warnings.push(...cssResult.warnings.map(warning => ({
        type: warning.type as any,
        message: `[CSS框架] ${warning.message}`,
        suggestion: warning.suggestion
      })))

      result.suggestions.push(...cssResult.suggestions.map(s => `[CSS框架] ${s}`))

      // 如果CSS兼容性很差，降低总分
      if (cssResult.score < 60) {
        result.score = Math.min(result.score, cssResult.score + 20)
      }

    } catch (error) {
      result.warnings.push({
        type: 'compatibility' as any,
        message: '[CSS框架] CSS框架兼容性验证失败',
        suggestion: '请检查CSS文件是否正确加载'
      })
    }
  }

  /**
   * 验证路径一致性
   */
  static validatePathConsistency(basePath: string, filePath: string, pageType: PageType): PageValidationResult {
    const result: PageValidationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      suggestions: [],
      score: 100
    }

    const rules = this.VALIDATION_RULES[pageType]
    const expectedPath = `pages/${basePath}/${this.getExpectedFileName(pageType)}`
    
    if (!rules.pathPattern.test(filePath)) {
      result.errors.push({
        type: 'path',
        message: `文件路径不符合规范: ${filePath}`,
        suggestion: `应该是: ${expectedPath}`
      })
    }

    if (!filePath.includes(basePath)) {
      result.errors.push({
        type: 'path',
        message: `文件路径与basePath不匹配: ${basePath}`,
        suggestion: `确保文件路径包含正确的basePath`
      })
    }

    result.score = this.calculateScore(result)
    result.isValid = result.errors.length === 0

    return result
  }

  /**
   * 验证JavaScript架构是否iframe兼容
   */
  static validateJavaScriptArchitecture(html: string): PageValidationResult {
    const result: PageValidationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      suggestions: [],
      score: 100
    }

    // 检查状态管理模式
    if (!html.includes('window.pageState')) {
      result.errors.push({
        type: 'javascript',
        message: '缺少iframe兼容的状态管理模式',
        suggestion: '使用 window.pageState = window.pageState || {} 模式'
      })
    }

    // 检查禁用的模式
    const forbiddenPatterns = [
      { pattern: /let\s+\w+\s*=/, message: '使用了let声明全局变量，可能导致重复声明错误' },
      { pattern: /var\s+\w+\s*=/, message: '使用了var声明全局变量，建议使用window对象' },
      { pattern: /window\.location\.href/, message: '使用了window.location.href，应使用window.top.location.hash' }
    ]

    for (const { pattern, message } of forbiddenPatterns) {
      if (pattern.test(html)) {
        result.errors.push({
          type: 'javascript',
          message,
          suggestion: '参考generate-page.md中的JavaScript架构规范'
        })
      }
    }

    result.score = this.calculateScore(result)
    result.isValid = result.errors.length === 0

    return result
  }

  private static checkBasicStructure(html: string, rules: PageValidationRules, result: PageValidationResult): void {
    // 检查HTML基本结构
    if (!html.includes('<!DOCTYPE html>')) {
      result.errors.push({
        type: 'structure',
        message: '缺少DOCTYPE声明',
        suggestion: '添加 <!DOCTYPE html>'
      })
    }

    if (!html.includes('<div id="app"')) {
      result.errors.push({
        type: 'structure',
        message: '缺少主容器 <div id="app">',
        suggestion: '添加 <div id="app" class="container"> 作为主容器'
      })
    }
  }

  private static checkCSSClasses(html: string, rules: PageValidationRules, result: PageValidationResult): void {
    for (const className of rules.requiredClasses) {
      if (!html.includes(`class="${className}"`) && !html.includes(`class='${className}'`)) {
        result.errors.push({
          type: 'class',
          message: `缺少必需的CSS类: ${className}`,
          suggestion: `确保使用正确的CSS类名: ${className}`
        })
      }
    }
  }

  private static checkRequiredElements(html: string, rules: PageValidationRules, result: PageValidationResult): void {
    for (const element of rules.requiredElements) {
      if (element.includes('.')) {
        // 带类名的元素检查
        const [tag, className] = element.split('.')
        const pattern = new RegExp(`<${tag}[^>]*class="[^"]*${className}[^"]*"`)
        if (!pattern.test(html)) {
          result.errors.push({
            type: 'element',
            message: `缺少必需的元素: ${element}`,
            suggestion: `添加 <${tag} class="${className}"> 元素`
          })
        }
      } else {
        // 普通元素检查
        if (!html.includes(`<${element}`)) {
          result.errors.push({
            type: 'element',
            message: `缺少必需的元素: ${element}`,
            suggestion: `添加 <${element}> 元素`
          })
        }
      }
    }
  }

  private static checkCSSFiles(html: string, rules: PageValidationRules, result: PageValidationResult): void {
    for (const cssFile of rules.cssFiles) {
      if (!html.includes(cssFile)) {
        result.warnings.push({
          type: 'style',
          message: `可能缺少CSS文件引用: ${cssFile}`,
          suggestion: `确保引用了 ${cssFile} 文件`
        })
      }
    }
  }

  private static checkJavaScriptArchitecture(html: string, rules: PageValidationRules, result: PageValidationResult): void {
    // 检查必需的JavaScript模式
    if (rules.jsPatterns) {
      for (const pattern of rules.jsPatterns) {
        if (!pattern.test(html)) {
          result.errors.push({
            type: 'javascript',
            message: `缺少必需的JavaScript模式: ${pattern.source}`,
            suggestion: '参考generate-page.md中的JavaScript架构规范'
          })
        }
      }
    }

    // 检查禁用的JavaScript模式
    if (rules.forbiddenJsPatterns) {
      for (const pattern of rules.forbiddenJsPatterns) {
        if (pattern.test(html)) {
          result.errors.push({
            type: 'javascript',
            message: `使用了禁用的JavaScript模式: ${pattern.source}`,
            suggestion: '使用iframe兼容的JavaScript架构'
          })
        }
      }
    }
  }

  private static checkPageSpecificRules(html: string, pageType: PageType, result: PageValidationResult): void {
    switch (pageType) {
      case 'list':
        this.checkListPageRules(html, result)
        break
      case 'form':
        this.checkFormPageRules(html, result)
        break
      case 'detail':
        this.checkDetailPageRules(html, result)
        break
    }
  }

  private static checkListPageRules(html: string, result: PageValidationResult): void {
    // 检查操作列是否包含"详情"按钮
    if (!html.includes('详情') && !html.includes('viewDetail')) {
      result.errors.push({
        type: 'element',
        message: '列表页面缺少"详情"按钮',
        suggestion: '在操作列添加"详情"按钮，调用viewDetail函数'
      })
    }

    // 检查表格结构
    if (!html.includes('<table') || !html.includes('<thead') || !html.includes('<tbody')) {
      result.errors.push({
        type: 'structure',
        message: '列表页面缺少完整的表格结构',
        suggestion: '确保包含table、thead、tbody元素'
      })
    }

    // 🔥 重点检查：操作列按钮样式
    this.checkActionButtonStyles(html, result)

    // 检查搜索区域
    if (!html.includes('search-area')) {
      result.errors.push({
        type: 'class',
        message: '列表页面缺少搜索区域',
        suggestion: '添加 <div class="search-area"> 搜索功能区域'
      })
    }

    // 检查操作按钮区域
    if (!html.includes('action-buttons')) {
      result.errors.push({
        type: 'class',
        message: '列表页面缺少操作按钮区域',
        suggestion: '添加 <div class="action-buttons"> 包装新建等操作按钮'
      })
    }
  }

  /**
   * 检查操作列按钮样式是否正确
   */
  private static checkActionButtonStyles(html: string, result: PageValidationResult): void {
    // 查找操作列中的按钮
    const actionButtonPattern = /<td[^>]*>[\s\S]*?(?:详情|编辑|删除|审核)[\s\S]*?<\/td>/g
    const actionCells = html.match(actionButtonPattern) || []

    if (actionCells.length === 0) {
      result.warnings.push({
        type: 'style',
        message: '未找到操作列，可能缺少操作按钮',
        suggestion: '确保表格包含操作列，包含详情、编辑、删除等按钮'
      })
      return
    }

    for (const cell of actionCells) {
      // 检查是否使用了正确的按钮样式 class="button text"
      if (!cell.includes('class="button text"') && !cell.includes("class='button text'")) {
        // 检查是否使用了错误的样式
        if (cell.includes('funi-btn funi-btn-text')) {
          result.errors.push({
            type: 'class',
            message: '操作列按钮使用了错误的CSS类名',
            suggestion: '将 class="funi-btn funi-btn-text" 改为 class="button text"'
          })
        } else if (cell.includes('<button') && !cell.includes('class="button text"')) {
          result.errors.push({
            type: 'class',
            message: '操作列按钮缺少正确的CSS类名',
            suggestion: '为操作列按钮添加 class="button text" 样式'
          })
        }
      }

      // 检查按钮是否有正确的事件处理
      const buttonActions = ['handleViewAction', 'handleEditAction', 'handleDeleteAction', 'handleAuditAction']
      let hasValidAction = false
      for (const action of buttonActions) {
        if (cell.includes(action)) {
          hasValidAction = true
          break
        }
      }

      if (!hasValidAction) {
        result.warnings.push({
          type: 'javascript',
          message: '操作列按钮可能缺少正确的事件处理函数',
          suggestion: '确保按钮使用 handleViewAction、handleEditAction 等标准事件处理函数'
        })
      }
    }
  }

  private static checkFormPageRules(html: string, result: PageValidationResult): void {
    // 检查表单容器结构
    if (!html.includes('form-container')) {
      result.errors.push({
        type: 'structure',
        message: '表单页面缺少form-container容器',
        suggestion: '使用 <div id="app" class="form-container"> 作为主容器'
      })
    }

    // 检查表单布局
    if (!html.includes('form-grid')) {
      result.errors.push({
        type: 'class',
        message: '表单页面缺少form-grid布局类',
        suggestion: '使用 <form class="form-grid"> 实现三列布局'
      })
    }

    // 检查表单分步结构（如果有）
    if (html.includes('form-step')) {
      this.checkFormStepStructure(html, result)
    }

    // 检查表单项结构
    if (!html.includes('form-item-row') || !html.includes('form-item-label') || !html.includes('form-item-value')) {
      result.errors.push({
        type: 'structure',
        message: '表单页面缺少标准的表单项结构',
        suggestion: '使用 form-item-row、form-item-label、form-item-value 类名构建表单项'
      })
    }

    // 检查必填项标识
    if (!html.includes('required')) {
      result.warnings.push({
        type: 'accessibility',
        message: '表单可能缺少必填项标识',
        suggestion: '为必填项添加required类名'
      })
    }

    // 检查表单操作按钮
    this.checkFormActionButtons(html, result)
  }

  /**
   * 检查表单分步结构
   */
  private static checkFormStepStructure(html: string, result: PageValidationResult): void {
    if (!html.includes('form-step-container')) {
      result.warnings.push({
        type: 'style',
        message: '分步表单缺少步骤容器',
        suggestion: '使用 <div class="form-step-container"> 包装步骤指示器'
      })
    }

    if (!html.includes('form-step-content')) {
      result.warnings.push({
        type: 'style',
        message: '分步表单缺少内容容器',
        suggestion: '使用 <div class="form-step-content"> 包装表单内容'
      })
    }
  }

  /**
   * 检查表单操作按钮
   */
  private static checkFormActionButtons(html: string, result: PageValidationResult): void {
    // 检查是否有提交、保存等操作按钮
    const actionKeywords = ['提交', '保存', '确定', '取消', '返回']
    let hasActionButton = false

    for (const keyword of actionKeywords) {
      if (html.includes(keyword)) {
        hasActionButton = true
        break
      }
    }

    if (!hasActionButton) {
      result.warnings.push({
        type: 'accessibility',
        message: '表单可能缺少操作按钮',
        suggestion: '添加提交、保存、取消等操作按钮'
      })
    }

    // 检查按钮是否使用了正确的样式
    if (html.includes('<button') && !html.includes('funi-btn')) {
      result.warnings.push({
        type: 'style',
        message: '表单按钮建议使用框架样式',
        suggestion: '为按钮添加 funi-btn 相关类名'
      })
    }
  }

  private static checkDetailPageRules(html: string, result: PageValidationResult): void {
    // 检查详情页面容器结构
    if (!html.includes('form-container')) {
      result.errors.push({
        type: 'structure',
        message: '详情页面缺少form-container容器',
        suggestion: '使用 <div id="app" class="form-container"> 作为主容器'
      })
    }

    // 检查详情页头部
    if (!html.includes('detail-header')) {
      result.errors.push({
        type: 'structure',
        message: '详情页面缺少detail-header头部区域',
        suggestion: '添加 <div class="detail-header"> 显示标题和状态信息'
      })
    }

    // 检查Tab切换结构
    if (!html.includes('funi-tabs')) {
      result.warnings.push({
        type: 'style',
        message: '详情页面建议使用Tab切换结构',
        suggestion: '使用 <div class="funi-tabs"> 实现基本信息和流程记录的切换'
      })
    }

    // 检查Tab项
    if (html.includes('funi-tabs') && !html.includes('tab-item')) {
      result.errors.push({
        type: 'structure',
        message: 'Tab容器缺少tab-item元素',
        suggestion: '在funi-tabs中添加 <div class="tab-item"> 元素'
      })
    }

    // 检查数据展示结构（复用表单结构）
    if (!html.includes('form-grid') || !html.includes('form-item-row')) {
      result.errors.push({
        type: 'structure',
        message: '详情页面缺少数据展示结构',
        suggestion: '使用 form-grid 和 form-item-row 结构展示详情数据'
      })
    }

    // 检查显示值容器
    if (!html.includes('display-value')) {
      result.warnings.push({
        type: 'style',
        message: '详情页面建议使用display-value类显示数据',
        suggestion: '使用 <div class="display-value"> 显示只读数据'
      })
    }

    // 检查流程记录区域（如果有）
    if (html.includes('流程记录') || html.includes('operation-log')) {
      this.checkOperationLogStructure(html, result)
    }
  }

  /**
   * 检查流程记录结构
   */
  private static checkOperationLogStructure(html: string, result: PageValidationResult): void {
    if (!html.includes('operation-log')) {
      result.warnings.push({
        type: 'style',
        message: '流程记录区域建议使用operation-log类',
        suggestion: '使用 <div class="operation-log"> 包装流程记录内容'
      })
    }

    if (html.includes('operation-log') && !html.includes('log-item')) {
      result.warnings.push({
        type: 'style',
        message: '流程记录缺少log-item结构',
        suggestion: '使用 <div class="log-item"> 包装每条流程记录'
      })
    }
  }

  private static calculateScore(result: PageValidationResult): number {
    let score = 100
    score -= result.errors.length * 15  // 每个错误扣15分
    score -= result.warnings.length * 5 // 每个警告扣5分
    return Math.max(0, score)
  }

  private static getExpectedFileName(pageType: PageType): string {
    const fileNames = {
      list: 'list.html',
      form: 'add-edit.html',
      detail: 'detail-review.html'
    }
    return fileNames[pageType]
  }
}

/**
 * 表单验证器
 * 专门验证表单页面的结构和规范
 */
export class FormValidator {

  /**
   * 验证表单结构是否符合规范
   */
  static validateFormStructure(html: string): PageValidationResult {
    const result: PageValidationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      suggestions: [],
      score: 100
    }

    // 检查表单基本结构
    this.checkFormBasicStructure(html, result)

    // 检查表单布局
    this.checkFormLayout(html, result)

    // 检查必填项标识
    this.checkRequiredFields(html, result)

    // 检查Select组件规范
    this.checkSelectComponents(html, result)

    // 检查表单CSS类名
    this.checkFormCSSClasses(html, result)

    result.score = this.calculateScore(result)
    result.isValid = result.errors.length === 0 && result.score >= 80

    return result
  }

  /**
   * 验证表单布局（三列布局）
   */
  static validateFormLayout(html: string): PageValidationResult {
    const result: PageValidationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      suggestions: [],
      score: 100
    }

    // 检查是否使用form-grid类
    if (!html.includes('form-grid')) {
      result.errors.push({
        type: 'class',
        message: '表单未使用form-grid类实现三列布局',
        suggestion: '使用 <form class="form-grid"> 实现标准三列布局'
      })
    }

    // 检查表单项结构
    if (!html.includes('form-item-row')) {
      result.errors.push({
        type: 'structure',
        message: '表单项未使用标准的form-item-row结构',
        suggestion: '使用 <div class="form-item-row"> 包装每个表单项'
      })
    }

    result.score = this.calculateScore(result)
    result.isValid = result.errors.length === 0

    return result
  }

  /**
   * 验证Select组件规范
   */
  static validateSelectComponents(html: string): PageValidationResult {
    const result: PageValidationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      suggestions: [],
      score: 100
    }

    // 检查Select元素是否包含multiple属性（应该禁止）
    const selectPattern = /<select[^>]*multiple[^>]*>/gi
    if (selectPattern.test(html)) {
      result.errors.push({
        type: 'element',
        message: 'Select元素不应包含multiple属性',
        suggestion: '根据generate-select.md规范，所有select元素都必须是单选'
      })
    }

    // 检查多选提示
    const selectElements = html.match(/<select[^>]*>/gi) || []
    for (const select of selectElements) {
      if (select.includes('多选') || select.includes('multi')) {
        // 检查是否有对应的提示信息
        if (!html.includes('form-item-tip')) {
          result.warnings.push({
            type: 'accessibility',
            message: '多选字段缺少提示信息',
            suggestion: '为多选字段添加form-item-tip提示："此为单选字段，如需多选请联系管理员"'
          })
        }
      }
    }

    result.score = this.calculateScore(result)
    result.isValid = result.errors.length === 0

    return result
  }

  private static checkFormBasicStructure(html: string, result: PageValidationResult): void {
    // 检查表单容器
    if (!html.includes('form-container')) {
      result.errors.push({
        type: 'structure',
        message: '缺少表单容器form-container',
        suggestion: '使用 <div class="form-container"> 作为表单外层容器'
      })
    }

    // 检查表单标题
    if (!html.includes('form-section-title')) {
      result.warnings.push({
        type: 'structure',
        message: '建议添加表单标题',
        suggestion: '使用 <div class="form-section-title"> 添加表单标题'
      })
    }

    // 检查form元素
    if (!html.includes('<form')) {
      result.errors.push({
        type: 'element',
        message: '缺少form元素',
        suggestion: '添加 <form class="form-grid"> 元素'
      })
    }
  }

  private static checkFormLayout(html: string, result: PageValidationResult): void {
    const requiredClasses = [
      'form-grid',
      'form-item-row',
      'form-item-label',
      'form-item-value'
    ]

    for (const className of requiredClasses) {
      if (!html.includes(className)) {
        result.errors.push({
          type: 'class',
          message: `缺少必需的表单CSS类: ${className}`,
          suggestion: `确保使用 ${className} 类名实现标准表单布局`
        })
      }
    }
  }

  private static checkRequiredFields(html: string, result: PageValidationResult): void {
    // 检查是否有必填项标识
    if (html.includes('required')) {
      // 检查必填项是否正确使用了required类
      const labelPattern = /<label[^>]*class="[^"]*required[^"]*"/gi
      if (!labelPattern.test(html)) {
        result.warnings.push({
          type: 'accessibility',
          message: '必填项标识可能未正确应用到label元素',
          suggestion: '为必填项的label添加required类：<label class="form-item-label required">'
        })
      }
    }

    // 检查是否有input-and-tip-wrapper结构
    if (html.includes('input') && !html.includes('input-and-tip-wrapper')) {
      result.warnings.push({
        type: 'structure',
        message: '建议使用input-and-tip-wrapper结构',
        suggestion: '使用 <div class="input-and-tip-wrapper"> 包装输入框和提示信息'
      })
    }
  }

  private static checkSelectComponents(html: string, result: PageValidationResult): void {
    // 检查select元素的结构
    const selectMatches = html.match(/<select[^>]*>[\s\S]*?<\/select>/gi) || []

    for (const selectHtml of selectMatches) {
      // 检查是否在input-and-tip-wrapper中
      const selectIndex = html.indexOf(selectHtml)
      const beforeSelect = html.substring(Math.max(0, selectIndex - 200), selectIndex)
      const afterSelect = html.substring(selectIndex + selectHtml.length, selectIndex + selectHtml.length + 200)

      if (!beforeSelect.includes('input-and-tip-wrapper') && !afterSelect.includes('</div>')) {
        result.warnings.push({
          type: 'structure',
          message: 'Select元素建议包装在input-and-tip-wrapper中',
          suggestion: '使用 <div class="input-and-tip-wrapper"> 包装select元素'
        })
      }
    }
  }

  private static checkFormCSSClasses(html: string, result: PageValidationResult): void {
    // 检查标签背景色设置
    if (html.includes('#f8f8f8')) {
      result.suggestions.push('检查标签背景色#f8f8f8是否支持深色主题切换')
    }

    // 检查表单操作按钮
    if (html.includes('button') && !html.includes('form-actions')) {
      result.warnings.push({
        type: 'style',
        message: '建议使用form-actions类包装表单操作按钮',
        suggestion: '使用 <div class="form-actions"> 包装提交、取消等按钮'
      })
    }
  }

  private static calculateScore(result: PageValidationResult): number {
    let score = 100
    score -= result.errors.length * 15
    score -= result.warnings.length * 5
    return Math.max(0, score)
  }
}
